//
//  OAuthViewController.swift
//  weibosina
//
//  Created by hwm on 16/8/28.
//  Copyright © 2016年 hwm. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController {

    let WB_App_ID = "88032644"
    let WB_App_Secret = "750cc70747835accf87925fa3d9595c1"
    let WB_redirect_urL = "http://www.babywong.top"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 1.初始化导航条
        setNav()

    }
    override func loadView() {
        webView.delegate = self
        view = webView
    }
    private lazy var webView: UIWebView = UIWebView()
    
    private func setNav() {
        navigationItem.title = "babywong微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(OAuthViewController.close))
        
        // 1.获取未授权的RequestToken
        // 要求SSL1.2
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_App_ID)&redirect_uri=\(WB_redirect_urL)"
        let url = NSURL.init(string: urlStr)
        webView.loadRequest(NSURLRequest.init(URL: url!))
        
    }
    
    func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
}

extension OAuthViewController: UIWebViewDelegate {
    
    // 返回ture正常加载 , 返回false不加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        /*
         加载授权界面: https://api.weibo.com/oauth2/authorize?client_id=2624860832&redirect_uri=http://www.520it.com
         跳转到授权界面: https://api.weibo.com/oauth2/authorize
         授权成功: http://www.520it.com/?code=91e779d15aa73698cbbb72bc7452f3b3
         取消授权: http://www.520it.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
         */
//        print(request.URL!.absoluteString)
        // 1.判断是否是授权回调页面, 如果不是就继续加载
        let urlString = request.URL!.absoluteString
        if !urlString.hasPrefix(WB_redirect_urL) {
            // 继续加载
            return true
        }
        // 2.判断是否授权成功
        let codeStr = "code="
        if request.URL!.query!.hasPrefix(codeStr) {
            // 授权成功
            // 1.取出已经授权的RequestToken
            // codeStr.endIndex是拿到code=最后的位置
            let code = request.URL!.query?.substringFromIndex(codeStr.endIndex)
            print("已经授权的RequestToken:\(code)")
            // 2.利用已经授权的RequestToken换取AccessToken
            loadAccessToken(code!)
        }else
        {
            // 取消授权
            print("取消授权")
            // 关闭界面
            close()
        }
        
        return false
    }
    
    /**
     换取AccessToken
     
     :param: code 已经授权的RequestToken
     */
    private func loadAccessToken(code: String) {
        // 1.定义路径
        let path = "oauth2/access_token"
        // 2.封装参数
        let params = ["client_id":WB_App_ID, "client_secret":WB_App_Secret, "grant_type":"authorization_code", "code":code, "redirect_uri":WB_redirect_urL]
        
        // 3.发送POST请求
        HttpTools.shareHttpTools().POST(path, parameters: params, success: { (task, JSON) in
            
            
            // 1.字典转模型
            let account = UserAccount(dict: JSON as! [String : AnyObject])
            account.loadUserInfo { (account, error) -> () in
                if account != nil
                {
                    account!.saveAccount()
                }
                
                SVProgressHUD.showInfoWithStatus("网络不给力", maskType: SVProgressHUDMaskType.Black)
            }

//            print(JSON)
            // 1.字典转模型
            /*
             plist : 特点只能存储系统自带的数据类型
             将对象转换为json之后写入文件中 --> 在公司中已经开始使用
             偏好设置: 本质plist
             归档 : 可以存储自定义对象
             数据库: 用于存储大数据 , 特点效率较高
             */
//            // 1.字典转模型
//            let account = UserAccount.init(dict: JSON as! [String : AnyObject])
//            
//            // 2.归档模型
//            account.saveAcount()
            
            }) { (task, error) in
                print(error)
        }
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showInfoWithStatus("正在加载...")
        SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.Black)
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    
    
}
